package com.reservation.controller;

import com.reservation.common.ApiResponse;
import com.reservation.dto.LoginRequest;
import com.reservation.dto.LoginResponse;
import com.reservation.dto.UserDTO;
import com.reservation.service.AuthService;
import com.reservation.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final JwtUtil jwtUtil;



    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        log.info("用户登录请求: username={}", request.getUsername());
        try {
            LoginResponse response = authService.login(request);
            return ApiResponse.success("登录成功", response);
        } catch (Exception e) {
            log.error("登录失败: username={}", request.getUsername(), e);
            return ApiResponse.error("登录失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ApiResponse<UserDTO> getCurrentUser(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return ApiResponse.error("未提供认证令牌");
            }

            if (!jwtUtil.validateToken(token)) {
                return ApiResponse.error("认证令牌无效");
            }

            String username = jwtUtil.getUsernameFromToken(token);
            UserDTO user = authService.getUserByUsername(username);
            return ApiResponse.success("获取用户信息成功", user);
        } catch (Exception e) {
            log.error("获取当前用户信息失败", e);
            return ApiResponse.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ApiResponse<String> logout() {
        log.info("用户登出");
        // JWT是无状态的，客户端删除token即可实现登出
        return ApiResponse.success("登出成功", "success");
    }

    /**
     * 从请求中提取JWT Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
